package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.help.PaasExcelExportHelp;
import com.xbongbong.paas.pojo.dto.ImportSmsDTO;
import com.xbongbong.paas.pojo.vo.ExcelTemplateVO;
import com.xbongbong.paas.pojo.vo.ImportSmsVO;
import com.xbongbong.paas.service.PaasExcelService;
import com.xbongbong.paas.service.SmsImportService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.OutputStream;
import java.util.Objects;

/**
 * 短信导入导出相关接口
 *
 * @author wufeng
 * @date 2018/9/21 10:57
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/file/excel")
public class SmsImportController {

    @Resource
    private SmsImportService smsImportService;
    @Resource
    private PaasExcelService paasExcelService;

    /**
     * 短信导入模板下载
     */
    @RequestMapping(value = "/template/download/sms")
    public String templateDownLoadSms(@RequestBody @Valid BaseDTO baseDTO, BindingResult br, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExcelTemplateVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            ExcelTemplateVO excelTemplateVO = new ExcelTemplateVO();
            try {
                excelTemplateVO = smsImportService.getSmsTemplate(baseDTO);
                httpServletResponse.reset();
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(excelTemplateVO.getName(), "utf-8"));
                OutputStream toClient = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
                excelTemplateVO.getWorkbook().write(toClient);
                toClient.flush();
                toClient.close();
                return null;
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            } finally {
                PaasExcelExportHelp.closeWorkBookException(excelTemplateVO.getWorkbook());
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 短信导入
     */
    @RequestMapping("/sms/importExcel")
    public String importPerformance(@ModelAttribute @Valid ImportSmsDTO importSmsDTO, BindingResult br) throws Exception {
        XbbResponse<ImportSmsVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                UserVO userVo = paasExcelService.getUserVo(importSmsDTO.getCorpid(), importSmsDTO.getUserId());
                importSmsDTO.setLoginUser(userVo);
                ImportSmsVO importSmsVO = smsImportService.importSmsData(importSmsDTO);
                response = new XbbResponse<>(importSmsVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response);
    }
}
